#!/bin/bash
script_path=$(cd "$(dirname "$0")" && pwd)
git_proxy=https://mirror.ghproxy.com/
node_version=1.7.0
pre_path=/opt/node_exporter
node_url=https://github.com/prometheus/node_exporter/releases/download/v${node_version}/node_exporter-${node_version}.linux-amd64.tar.gz
command -v jq >>/dev/null && country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | jq -r ".country") || country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | grep country | awk -F '"' '{print $4}')

node_download() {
  if [ "$country" == "CN" ]; then
    curl -O ${git_proxy}${node_url}
  else
    curl -O ${node_url}
  fi
}

node_install() {
  tar xf node_exporter-${node_version}.linux-amd64.tar.gz -C /opt
  ln -sf /opt/node_exporter-${node_version}.linux-amd64 ${pre_path}
}

node_config() {
  cat >/usr/lib/systemd/system/node_exporter.service <<"EOF"
[Unit]
Description=NodeExporter
After=network-online.target

[Service]
Type=simple
ExecStart=/opt/node_exporter/node_exporter
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
}

main() {
  [ -f node_exporter-${node_version}.linux-amd64.tar.gz ] || node_download
  node_install
  node_config
  systemctl daemon-reload
  systemctl enable --now node_exporter
  if [ $(systemctl is-active node_exporter) == "active" ]; then
    echo "node_exporter is running,deleting node_exporter archive"
    rm -rf ${script_path}/prometheus-${node_version}.linux-amd64.tar.gz
  else
    echo "node_exporter failed,please check!!!"
  fi
}
main
